package com.example.term;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class chat extends Fragment {

    public chat() {
        // Required empty public constructor
    }
    EditText txt_ip,txt_port,txt_zhenceport,txt_getmassage;
    TextView txt_show;
    Button btn_ok,btn_sent;
    String sendmessage,ip;
    InetAddress inetaddress= null;
    DatagramPacket pack;
    DatagramSocket sendsocket=null,receivesocket=null;
    Message m;
    int receiveport,zhenceport;
    static final int RECEIVE_WHAT=1,SEND_WHAT=2;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_chat, container, false);
    }
    public void onActivityCreated(@Nullable Bundle   savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        txt_ip = (EditText) getActivity().findViewById(R.id.txt_ip);  // ip
        txt_port = (EditText) getActivity().findViewById(R.id.txt_port);
        txt_zhenceport = (EditText) getActivity().findViewById(R.id.txt_zhenceport);
        txt_getmassage = (EditText) getActivity().findViewById(R.id.txt_getmassage);

        txt_show = (TextView) getActivity().findViewById(R.id.txt_show);
        btn_ok = (Button) getActivity().findViewById(R.id.btn_ok);
        btn_sent =(Button) getActivity().findViewById(R.id.btn_sent);
        txt_show.setMovementMethod(ScrollingMovementMethod.getInstance());
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ip = txt_ip.getText().toString();
                receiveport = Integer.parseInt(txt_port.getText().toString());
                zhenceport = Integer.parseInt(txt_zhenceport.getText().toString());
                new Thread(new ReceiveMessage()).start();
            }
        });
        btn_sent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendmessage = txt_getmassage.getText().toString();
                new Thread(new SendMessage()).start();
            }
        });
    }
    public class SendMessage implements Runnable{

        @Override
        public void run() {

            byte[] buffer = sendmessage.getBytes();
            try {


                inetaddress = InetAddress.getByName(ip);


                pack = new DatagramPacket(buffer,buffer.length,inetaddress,receiveport);
                sendsocket = new DatagramSocket();
                sendsocket.send(pack);
            } catch (UnknownHostException ex) {
                ex.printStackTrace();
            }
            catch (SocketException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

            Bundle bundle = new Bundle();
            bundle.putString("send",sendmessage);
            m = new Message();
            m.what = SEND_WHAT;
            m.setData(bundle);

            handler.sendMessage(m);
            sendsocket.close();
        }
    }
    public class ReceiveMessage implements Runnable{
        byte data[] = new byte[8192];
        String message = null,str;

        @Override
        public void run() {
            pack = new DatagramPacket(data,data.length);
            try {
                receivesocket = new DatagramSocket(null);
                receivesocket.setReuseAddress(true);
                receivesocket.bind(new InetSocketAddress(zhenceport));
            } catch (SocketException e) {
                e.printStackTrace();
            }
            while(!"quit".equalsIgnoreCase(message))
            {
                try {
                    receivesocket.receive(pack);
                    message = new String(pack.getData(),0,pack.getLength());
                    str = pack.getAddress().getHostAddress();
                    m = new Message();
                    m.what=RECEIVE_WHAT;

                    Bundle bundle = new Bundle();
                    bundle.putString("receiveip",str);
                    bundle.putString("receivedata",message);
                    m.setData(bundle);
                    Thread.sleep(100);
                    handler.sendMessage(m);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            receivesocket.close();
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch(msg.what){
                case RECEIVE_WHAT:
//                    txt_show.setGravity(Gravity.LEFT);
                    txt_show.append("收到"+msg.getData().getString("receiveip")+"的消息："+
                            msg.getData().getString("receivedata")+"\n");

                    break;
                case SEND_WHAT:
//                    txt_show.setGravity(Gravity.RIGHT);
                    txt_show.append("发送的消息："+msg.getData().getString("send").toString()+"\n");

                    break;
            }
        }
    };

}